package com.weai.controller;

import com.weai.dto.ApiResponse;
import com.weai.dto.AuthResponse;
import com.weai.dto.LoginRequest;
import com.weai.dto.RegisterRequest;
import com.weai.dto.UserDTO;
import com.weai.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户相关操作接口")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    
    private final UserService userService;
    
    /**
     * 注册新用户
     *
     * @param request 注册请求
     * @return 认证响应
     */
    @PostMapping("/register")
    @ResponseStatus(HttpStatus.CREATED)
    @Operation(summary = "注册新用户", description = "注册一个新用户并返回JWT令牌和用户信息")
    public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        log.info("接收到注册请求: {}", request.getEnglishName());
        AuthResponse response = userService.register(request);
        return ApiResponse.success("注册成功", response);
    }
    
    /**
     * 用户登录
     *
     * @param request 登录请求
     * @return 认证响应
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录并返回JWT令牌和用户信息")
    public ApiResponse<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("接收到登录请求: {}", request.getEnglishName());
        AuthResponse response = userService.login(request);
        return ApiResponse.success("登录成功", response);
    }
    
    /**
     * 获取所有用户
     *
     * @return 用户列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "获取所有用户", description = "获取系统中所有用户的信息（仅管理员可访问）")
    public ApiResponse<List<UserDTO>> getAllUsers() {
        log.info("接收到获取所有用户请求");
        List<UserDTO> users = userService.findAll();
        return ApiResponse.success("查询成功", users);
    }
    
    /**
     * 获取所有用户的英文名和中文名
     *
     * @return 用户名称列表 格式：englishName/chineseName
     */
    @GetMapping("/names")
    @Operation(summary = "获取所有用户名称", description = "获取所有用户的英文名和中文名，格式为englishName/chineseName")
    public ApiResponse<List<String>> getAllUserNames() {
        log.info("接收到获取所有用户名称请求");
        List<String> userNames = userService.findAllUserNames();
        return ApiResponse.success("查询成功", userNames);
    }
    
    /**
     * 根据英文名获取用户
     *
     * @param englishName 英文名
     * @return 用户信息
     */
    @GetMapping("/by-name/{englishName}")
    @Operation(summary = "根据英文名获取用户", description = "根据用户英文名获取用户信息")
    public ApiResponse<UserDTO> getUserByEnglishName(
            @Parameter(description = "用户英文名", required = true) @PathVariable String englishName) {
        log.info("接收到根据英文名获取用户请求: {}", englishName);
        UserDTO user = userService.findByEnglishName(englishName);
        return ApiResponse.success("查询成功", user);
    }
    
    /**
     * 根据ID获取用户
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户信息")
    public ApiResponse<UserDTO> getUserById(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        log.info("接收到根据ID获取用户请求: {}", id);
        UserDTO user = userService.findById(id);
        return ApiResponse.success("查询成功", user);
    }
    
    /**
     * 更新用户信息
     *
     * @param id      用户ID
     * @param userDTO 用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新用户信息", description = "根据用户ID更新用户信息")
    public ApiResponse<UserDTO> updateUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id,
            @Valid @RequestBody UserDTO userDTO) {
        log.info("接收到更新用户请求: {}", id);
        UserDTO updatedUser = userService.update(id, userDTO);
        return ApiResponse.success("更新成功", updatedUser);
    }
    
    /**
     * 删除用户
     *
     * @param id 用户ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户（仅管理员可访问）")
    public ApiResponse<Void> deleteUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        log.info("接收到删除用户请求: {}", id);
        userService.delete(id);
        return ApiResponse.success("删除成功", null);
    }
} 